package me.suntao.javaio.client.bio;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by suntao on 2017/6/2.
 */
public class BioClient {
  /**
   * 服务端口号
   */
  private static final int DEFAULT_PORT = 28000;
  /**
   * 模拟客户端数量
   */
  private static final int CLIENT_COUNT = 20;
  public static void main(String[] args) throws IOException {
    CyclicBarrier cyclicBarrier = new CyclicBarrier(CLIENT_COUNT);
    for (int i=0;i<CLIENT_COUNT;i++){
      new Thread(new ClientThread(cyclicBarrier)).start();
    }
  }

  static class ClientThread implements Runnable{

    private final Socket socket = new Socket("127.0.0.1",DEFAULT_PORT);

    CyclicBarrier barrier;

    ClientThread(CyclicBarrier barrier) throws IOException {
      this.barrier=barrier;
    }

    public void run() {
      try {
        barrier.await();
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        String msg = String.format("clientname:%s, senttime:%s",Thread.currentThread().getName(),System.currentTimeMillis());
        System.out.println("clientname:"+Thread.currentThread().getName()+", currentTime:"+System.currentTimeMillis()+"start send msg");
        outputStream.writeUTF(msg);
        outputStream.flush();
        socket.close();
        System.out.println("clientname:"+Thread.currentThread().getName()+", currentTime:"+System.currentTimeMillis()+"start done other things");
      } catch (IOException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
    }
  }

}
